package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private WorkspaceService workspaceService;

    /*
     * 营业额统计
     * */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        /*
         * 获取日期列表
         * */
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        /*
         * 统计每日的营业额
         * */
        List<Double> StatisticsList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //把LocalDate转成LocalDateTime,获取当天最大时间和最小时间
            // 当天的开始时间（00:00:00）
            LocalDateTime startOfDay = localDate.atStartOfDay();

            // 当天的结束时间（23:59:59.999999999）
            LocalDateTime endOfDay = localDate.plusDays(1).atStartOfDay().minusNanos(1);
            Map map = new HashMap();
            map.put("begin", startOfDay);
            map.put("end", endOfDay);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.sumByMap(map);
            amount = amount == null ? 0 : amount;
            StatisticsList.add(amount);
        }
        return new TurnoverReportVO().builder().dateList(StringUtils.join(dateList, ",")).turnoverList(StringUtils.join(StatisticsList, ",")).build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        /*
         * 用户总量
         * */
        List<Integer> totalUser = new ArrayList<>();
        List<Integer> newUser = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            // 当天的开始时间（00:00:00）
            LocalDateTime startOfDay = localDate.atStartOfDay();
            // 当天的结束时间（23:59:59.999999999）
            LocalDateTime endOfDay = localDate.plusDays(1).atStartOfDay().minusNanos(1);
            /*
             * 截止到现在的用户总量
             * */
            Map map = new HashMap();
            map.put("endTime", endOfDay);
            Integer total = userMapper.countByMap(map);
            totalUser.add(total);
            /*
             * 今日新增用户量
             * */
            map.put("beginTime", startOfDay);
            Integer today = userMapper.countByMap(map);
            newUser.add(today);
        }

        return UserReportVO.builder().totalUserList(StringUtils.join(totalUser, ",")).newUserList(StringUtils.join(newUser, ",")).dateList(StringUtils.join(dateList, ",")).build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        /*
         * 每日订单数
         * */
        List<Integer> orderCountList = new ArrayList();
        List<Integer> validOrderCountList = new ArrayList();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        double orderCompletionRate = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer orders = orderMapper.countByMap(map);
            orderCountList.add(orders);
            map.put("status", Orders.COMPLETED);
            Integer validOrders = orderMapper.countByMap(map);
            validOrderCountList.add(validOrders);
        }
        totalOrderCount = orderCountList.stream()
                .mapToInt(Integer::intValue) // 转换为 int 类型流
                .sum();// 累加

        validOrderCount = validOrderCountList.stream().mapToInt(Integer::intValue).sum();

        if(totalOrderCount != 0){
            orderCompletionRate = Double.valueOf(validOrderCount) / Double.valueOf(totalOrderCount);
        }

        return OrderReportVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .dateList(StringUtils.join(dateList, ","))
                .build();
    }

    @Override
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {
        Map map = new HashMap<>();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> salesTop10ByMap1 = orderMapper.getSalesTop10ByMap1(map);
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(salesTop10ByMap1.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ","))
                .numberList(StringUtils.join(salesTop10ByMap1.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询数据库获取营业数据,最近30天
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模版文件创建一个新的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取sheet页
        XSSFSheet sheet1 = excel.getSheet("Sheet1");
        //填充数据--时间
        sheet1.getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);

        //获得第4行
        XSSFRow row = sheet1.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet1.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());

        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            //获得某一行
            row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData1.getTurnover());
            row.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData1.getUnitPrice());
            row.getCell(6).setCellValue(businessData1.getNewUsers());
        }


        //通过输出流把Excel下载到客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);
        outputStream.close();
        excel.close();

    }
}
